function [CenteredPics, ROIStart_X, ROIStart_Y] = centerPics(Pics)
%centerPics Centers a stack of pictures around their combined
%center of mass.
%
%   [CenteredPics,ROIStart_X,ROIStart_Y] = centerPics(obj,Pics)
%   Given Pics, an Ny x Nx x NImgs, return an array of the same
%   size which is centered on the combined center of mass of
%   the image stack. ROIStart_X and ROIStart_Y give the
%   coordinate of the upper left most point in CenteredPics in
%   terms of the initial array, Pics. This coordinate is not
%   necessarily in the initial array, which is treated as if it
%   is padded by zeros.

%get array of centers
%             [Cxs,Cys,~,~,~] = obj.getCenterMass(Pics);
[Cxs, Cys, ~] = get_moment(Pics, 1, [], []);
%center coordinate
Ix = (size(Pics, 2) - 1) / 2;
Iy = (size(Pics, 1) - 1) / 2;
XShifts = floor(Ix - Cxs);
YShifts = floor(Iy - Cys);

NImgs = size(Pics,3);
for ii = 1:NImgs
    try
        PixelsToMoveX = XShifts(ii); %floor(Ix-Cxs(ii));
        PixelsToMoveY = YShifts(ii); %floor(Iy-Cys(ii));
        %                     Pics(:,:,ii) = obj.getShiftedMat(Pics(:,:,ii),PixelsToMoveX,PixelsToMoveY,0);
        Pics(:,:,ii) = getShiftedMat(Pics(:, :, ii), PixelsToMoveX, PixelsToMoveY, 0);
    catch
        Pics(:,:,ii) = NaN(size(Pics,1),size(Pics,2));
    end
end

%remove failed images from stack
NanImages = squeeze(all(all(isnan(Pics),1),2));
ImgIndicesToRemove = find(NanImages);
Pics(:,:,ImgIndicesToRemove) = [];

XShifts(ImgIndicesToRemove) = [];
YShifts(ImgIndicesToRemove) = [];

ROIStart_X = 1 - XShifts;
ROIStart_Y = 1 - YShifts;
%TODO decide what to do with XShifts/YShifts...
CenteredPics = Pics;
end